import json

from django.core.serializers import serialize
from django.http import JsonResponse
from django.http import HttpResponse
from django.shortcuts import render

from app.dto.BoatBatteryInfoDto import BoatBatteryInfoDto
from app.dto.UserDto import UserDto
from app.models import User, BoatBatteryInfo, BoatSingleBattery
from common.result import Result

from django.core import serializers

from pcs_app import mqttManager

from decimal import Decimal

from django.core.serializers.json import DjangoJSONEncoder


def getMqttData(request):
    # 处理请求逻辑
    data = {1: 'value'}
    # data = {
    #     'message': 'Hello, World!',
    #     'number': 42,
    # }

    # 创建 JSONResponse 对象并返回
    response = Result(code=200, msg='Success', data=Result(200, "success", "1"))
    result = json.dumps(response, default=lambda o: o.__dict__, indent=4)

    mqttManager.mqtt_publish("device01/01", "1324546576574587")
    return HttpResponse(result)


def login(request):
    if request.method == 'POST':
        obj = json.loads(request.body)
        username = obj.get('username', None)
        password = obj.get('password', None)

        if username is None or password is None:
            return JsonResponse({'code': 500, 'message': '请求参数错误'})

        userBean = User.objects.filter(user_name=username).get()

        if userBean is None:
            return HttpResponse(
                json.dumps(Result(code=500, msg='用户名不存在', data=None), default=lambda o: o.__dict__, indent=4))

        if (password != userBean.user_password):
            return HttpResponse(
                json.dumps(Result(code=500, msg='密码错误', data=None), default=lambda o: o.__dict__, indent=4))

        # 根据 userid 查询 pcs_sn
        response = Result(code=200, msg='Success',
                          data=UserDto(userBean.user_name, userBean.nick_name, userBean.address, userBean.age,
                                       "7CDFA1D0A90E", "7CDFA1D0A90E"))
        result = json.dumps(response, default=lambda o: o.__dict__, indent=4)
        return HttpResponse(result)

    # return JsonResponse({'code': 500, 'message': '账号或密码错误'})


class DecimalEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, Decimal):
            return float(obj)
        return json.JSONEncoder.default(self, obj)


def batteryInfos(request):
    if request.method == 'POST':
        obj = json.loads(request.body)
        bms_sn = obj.get('bms_sn', None)

        if bms_sn is None:
            return JsonResponse({'code': 500, 'message': '请求参数错误'})

        try:
            bmsBean = BoatBatteryInfo.objects.filter(bms_sn=bms_sn).get()
        except BoatBatteryInfo.DoesNotExist:
            return HttpResponse(
                json.dumps(Result(code=500, msg='用户名不存在', data=None), default=lambda o: o.__dict__, indent=4,
                           ensure_ascii=False))
        except BoatBatteryInfo.MultipleObjectsReturned:
            print("找到多条匹配记录")

        response = Result(code=200, msg='Success',
                          data=BoatBatteryInfoDto(bms_soc=float(bmsBean.bms_soc), bms_soh=float(bmsBean.bms_soh),
                                                  remaining_battery=float(bmsBean.remaining_battery),
                                                  total_voltage=float(bmsBean.total_voltage),
                                                  rated_voltage=float(bmsBean.rated_voltage),
                                                  current=float(bmsBean.current),
                                                  max_current=float(bmsBean.max_current),
                                                  min_temp=float(bmsBean.min_temp), max_temp=float(bmsBean.max_temp),
                                                  min_voltage=float(bmsBean.min_voltage),
                                                  max_voltage=float(bmsBean.max_voltage),
                                                  cluster_count=bmsBean.cluster_count))
        result = json.dumps(response, default=lambda o: o.__dict__, indent=4, cls=DecimalEncoder, ensure_ascii=False)
        return HttpResponse(result)


def batterySingleInfos(request):
    if request.method == 'POST':
        obj = json.loads(request.body)
        bms_sn = obj.get('bms_sn', None)

        if bms_sn is None:
            return JsonResponse({'code': 500, 'message': '请求参数错误'})

        try:
            # 使用 values 方法获取包含 Decimal 类型的 QuerySet
            bmsBeans = BoatSingleBattery.objects.filter(bms_sn=bms_sn).values()

            # 将 Decimal 类型字段转换为 Python 原生的数据类型
            serialized_data = []
            for item in bmsBeans:
                serialized_item = {
                    'bms_sn': item['bms_sn'],
                    'cluster_id': item['cluster_id'],
                    'battery_num': item['battery_num'],
                    'battery_voltage': float(item['battery_voltage']),
                    'battery_temp': float(item['battery_temp']),
                    'create_time': item['create_time'],
                    'update_time': item['update_time'],
                }
                serialized_data.append(serialized_item)

            # 将 Python 原生数据类型序列化为 JSON
            json_data = json.dumps(serialized_data, cls=DjangoJSONEncoder, indent=4, ensure_ascii=False)
            return JsonResponse({'code': 200, 'data': json_data})
            # parsed_data = json.loads(json.dumps(serialized_data, cls=DjangoJSONEncoder, indent=4, ensure_ascii=False))
            # return JsonResponse({'code': 200, 'data': serialized_data}, safe=True)
            # return HttpResponse(serialized_data)
        except BoatBatteryInfo.DoesNotExist:
            return JsonResponse({'code': 500, 'message': '未找到匹配记录'})
